package queue;

import com.google.common.base.Preconditions;

import java.util.Collection;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author MeiZhongHao
 * @create_date 2022/11/18 15 09
 **/
public class BatchQueue {


    /**
     * 批量获取队列数据，思考写法的时候有了思路，却在guava里找到了相同的实现。便将实现方法拎出来，方便记忆
     * from Queues.drain
     * @param q
     * @param buffer
     * @param numElements
     * @param timeout
     * @param unit
     * @param <E>
     * @return
     * @throws InterruptedException
     */
    public static <E> int drain(BlockingQueue<E> q, Collection<? super E> buffer, int numElements, long timeout, TimeUnit unit) throws InterruptedException {
        Preconditions.checkNotNull(buffer);
        long deadline = System.nanoTime() + unit.toNanos(timeout);
        int added = 0;

        while (added < numElements) {
            added += q.drainTo(buffer, numElements - added);
            if (added < numElements) {
                E e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS);
                if (e == null) {
                    break;
                }

                buffer.add(e);
                ++added;
            }
        }

        return added;
    }


}
